<template>
  <div id="AutoDiscover">
    <el-card class="mt10">
      <!-- 搜索条件 -->
      <el-form :inline="true" class="demo-form-inline" size="mini" ref="query">
        <el-form-item label="名称">
          <el-input
            class="mr10"
            v-model="query.name"
            size="mini"
            placeholder="请输入名称"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="请选择">
            <el-option label="启用" :value="0"> </el-option>
            <el-option label="禁用" :value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="ml10" size="mini" type="primary" @click="getList()"
            >搜索</el-button
          >
          <el-button
            class="ml10"
            size="mini"
            type="warning"
            plain
            @click="resize()"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-button
        size="mini"
        type="primary"
        @click="dialogVisible = true"
        v-hasPermi="['automated:script:add']"
        >添加自愈</el-button
      >
      <el-button
        size="mini"
        type="danger"
        :disabled="multipleSelection.length == 0"
        @click="delAction"
        >删除</el-button
      >

      <!-- 列表 -->
      <el-table
        class="mt20"
        :data="tableData"
        style="width: 100%"
        :cell-style="cellStyle"
        height="calc(100vh - 220px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="left" />
        <el-table-column
          width="80"
          prop="name"
          align="left"
          label="名称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="conditions"
          align="left"
          label="条件"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div
              style="font-weight: bold"
              class="mb10"
              v-for="(item, index) in scope.row.conditions"
              :key="index"
            >
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="operations"
          align="left"
          label="操作"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div
              style="font-weight: bold"
              class="mb10"
              v-for="(item, index) in scope.row.operations"
              :key="index"
            >
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          prop="status"
          align="center"
          label="状态"
          show-overflow-tooltip
        >
          <template slot-scope="scope"
            ><el-tag :type="scope.row.status == 0 ? 'success' : 'warning'">
              {{ scope.row.status == 0 ? "启用" : "禁用" }}</el-tag
            ></template
          >
        </el-table-column>
        <el-table-column width="100" label="修改状态" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="showEdit(scope.row)" size="small"
              >修改状态</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="this.total"
        :page.sync="query.pageNum"
        :limit.sync="query.pageSize"
        @pagination="getList()"
      />

      <el-dialog title="修改状态" :visible.sync="editVisible">
        <el-form :model="editForm" ref="editForm" :rules="rules">
          <el-form-item label="状态" prop="status">
            <el-select v-model="editForm.status" placeholder="请选择状态">
              <el-option label="禁用" :value="1"></el-option>
              <el-option label="启用" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editAction('editForm')"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- 添加自愈弹窗 -->
      <el-dialog
        title="添加自愈"
        :visible.sync="dialogVisible"
        width="40%"
        @close="closeDialog('form')"
      >
        <el-form
          :rules="rules"
          label-width="110px"
          ref="form"
          :model="form"
          size="mini"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入自愈名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择操作主机" prop="operationHostId">
            <!-- <el-select v-model="form.operationHostId" placeholder="请选择脚本">
              <el-option
                :label="item.name"
                :value="item.name"
                v-for="item in script_data"
                :key="item"
              ></el-option>
            </el-select> -->
            <el-select
              v-model="form.operationHostId"
              multiple
              multiple-limit="1"
              placeholder="请选择操作主机"
            >
              <el-option
                v-for="item in hosts"
                :key="item.hostid"
                :label="item.host"
                :value="item.hostid"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="条件" prop="conditions">
            <div class="condition_box">
              <table style="width: 100%; font-size: 12px">
                <thead style="text-align: left; color: #768d99">
                  <th>标签</th>
                  <th>名称</th>
                  <th>动作</th>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in conditionList" :key="index">
                    <td>{{ letterArr[index] }}</td>
                    <td>
                      {{
                        "触发器 " +
                        (item.triggerOperator == 0 ? "等于 " : "不等于 ") +
                        item.name
                      }}
                    </td>
                    <td style="color: #1890ff; cursor: pointer">移除</td>
                  </tr>
                  <tr>
                    <td
                      style="color: #1890ff; cursor: pointer"
                      @click="dialogVisible_condition = true"
                    >
                      添加
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </el-form-item>
          <el-form-item label="选择脚本" prop="scriptId">
            <el-select v-model="form.scriptId" placeholder="请选择脚本">
              <el-option
                :label="item.name"
                :value="item.scriptId"
                v-for="item in script_data"
                :key="item.scriptId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('form')"
            >确 定</el-button
          >
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>

      <!-- 添加触发条件弹窗 -->
      <el-dialog
        title="新的触发条件"
        :visible.sync="dialogVisible_condition"
        width="30%"
        @close="closeDialog('form_condition')"
      >
        <el-form
          :rules="rules"
          label-width="60px"
          ref="form_condition"
          :model="form_condition"
          size="mini"
        >
          <el-form-item label="类型" prop="flag">
            <el-select v-model="form_condition.flag" disabled>
              <el-option label="触发器" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="操作者" prop="triggerOperator">
            <el-radio-group
              v-model="form_condition.triggerOperator"
              size="mini"
            >
              <el-radio-button label="0">等于</el-radio-button>
              <el-radio-button label="1">不等于</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="触发器" prop="trigger_inp">
            <div class="trigger_box">
              <div class="trigger_inp">
                <div
                  class="choosed_Triggers"
                  v-for="(item, index) in form_condition.trigger_inp"
                  :key="index"
                >
                  {{ item.name }}
                </div>
              </div>
              <el-button class="ml10" @click="dialogVisible_trigger = true"
                >选择</el-button
              >
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitCondition">确 定</el-button>
          <el-button @click="dialogVisible_condition = false">取 消</el-button>
        </span>
      </el-dialog>

      <!-- 选择触发器的弹窗 -->
      <el-dialog
        title="触发器"
        :visible.sync="dialogVisible_trigger"
        width="50%"
        :before-close="handleClose"
      >
        <!-- <el-form
          :rules="rules"
          label-width="60px"
          ref="form_trigger"
          :model="form_trigger"
          size="mini"
        >
          <el-form-item label="主机" prop="host">
            <el-select v-model="form_trigger.host">
              <el-option
                v-for="item in hosts"
                :key="item.hostid"
                :label="item.host"
                :value="item.hostid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form> -->
        <el-table
          :data="trigger_tableData"
          size="mini"
          height="calc(100vh - 300px)"
          :cell-style="cellStyle"
          @selection-change="handleSelectionChange"
          ref="multipleTable"
        >
          >
          <el-table-column type="selection" width="50"> </el-table-column>
          <el-table-column prop="description" label="名称" align="left">
          </el-table-column>
          <el-table-column
            prop="priority"
            label="严重性"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <el-tag :type="scope.row.priority < 3 ? 'warning' : 'danger'">{{
                scope.row.priority | getPriority
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="70">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status == '0' ? 'success' : 'danger'">{{
                scope.row.status == "0" ? "已启用" : "已禁用"
              }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="chooseTrigger">选 择</el-button>
          <el-button @click="dialogVisible_trigger = false">取 消</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getHostSearch_Api, //获取主机列表
} from "@/api/automated/host";
import {
  getTrigger_Api, //触发器查询
} from "@/api/automated/host.js";
import {
  addAction_Api, //添加自愈
  getActionList_Api, //故障自愈列表
  delAction_Api, //故障自愈批量删除
  editAction_Api, //故障自愈状态修改
} from "@/api/automated/selfHealing.js";
import {
  getScriptList_Api, //脚本列表
} from "@/api/automated/script.js";
/* import {
  getScriptList_Api, //脚本列表
} from "@/api/automated/host.js"; */
import Template from "../../ConfigurationManagement/model/Template.vue";

export default {
  components: { Template },
  data() {
    return {
      total: 0,
      editVisible: false,
      editForm: {
        actionid: "",
        status: "",
      },
      query: {
        pageSize: "10",
        pageNum: "1",
        status: "",
        name: "",
      },
      multipleSelection: [], //多选
      //故障自愈表格数据
      tableData: [],
      //条件表格数据
      conditionList: [],
      hosts: [], //主机数据
      //触发器表格数据
      trigger_tableData: [],
      //脚本数据
      script_data: [],
      //控制添加自愈弹窗显示隐藏
      dialogVisible: false,
      //控制新的触发条件弹窗
      dialogVisible_condition: false,
      //选择触发器弹窗
      dialogVisible_trigger: false,
      //添加自愈表单
      form: {
        name: null, //名称
        scriptId: null, //脚本
        operationHostId: [], //操作主机id集合
        hostIds: [], //主机集合
        triggerId: [], //触发器id集合
        conditions: null, //条件字符串
        operations: null, //条件字符串
      },
      //添加触发条件表单
      form_condition: {
        flag: "2", //类型
        hostOperator: "0", //操作者
        triggerOperator: "0", //操作者
        //触发器输入框
        trigger_inp: [],
      },
      //触发器表单
      form_trigger: {
        host: null, //主机
      },
      //验证规则
      rules: {
        //名称
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        //表达式
        scriptId: [
          { required: true, message: "请选择脚本", trigger: "change" },
        ],
        //添加表达式的监控项
        flag: [{ required: true, message: "请选择", trigger: "blur" }],
        //操作主机id集合
        operationHostId: [
          { required: true, message: "请选择操作主机", trigger: "change" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        conditions: [
          { required: true, message: "请添加条件", trigger: "change" },
        ],
      },
      letterArr: Array.from({ length: 26 }, (_, i) =>
        String.fromCharCode("A".charCodeAt(0) + i)
      ),
    };
  },
  methods: {
    resize() {
      this.query.name = "";
      this.query.status = "";
      this.getList();
    },
    //获取故障自愈列表
    getList() {
      getActionList_Api(this.query).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
        this.tableData.forEach((item) => {
          item.conditions = item.conditions.split(",");
          item.operations = item.operations.split(",");
        });
      });
    },
    //获取主机列表数据
    async getHostList() {
      getHostSearch_Api(this.query).then((res) => {
        this.hosts = res.rows;
      });
    },
    //获取触发器数据
    getTriggerList(hostid) {
      getTrigger_Api({
        output: "extend",
        hostids: String(hostid),
        selectTags: "extend",
      }).then((res) => {
        this.trigger_tableData = res.data;
      });
    },
    //获取脚本列表数据
    getListData() {
      getScriptList_Api({ pageNum: 1, pageSize: 1000, scope: 1 }).then(
        (res) => {
          this.script_data = res.rows;
        }
      );
    },
    //设置监控项列表样式
    cellStyle({ row, column, columnIndex }) {
      if (columnIndex === 1) {
        return "color:#409eff;cursor:pointer";
      } else {
        return "";
      }
    },
    //提交表单
    submitForm(formName) {
      //处理条件和操作字符串
      const ConditionsArr = []; //条件
      const operationArr = []; //操作
      //操作
      //先根据脚本id找到脚本
      const script = this.script_data.find(
        (item) => item.scriptId == this.form.scriptId
      );
      this.form.operationHostId.forEach((item) => {
        const operationHost = this.hosts.find((ele) => item == ele.hostid);
        operationArr.push(
          "Run script " + script.name + " on hosts:" + operationHost.host
        );
      });
      this.form.operations = operationArr.join(",");
      //处理hostIds 和 triggerId
      this.form.hostIds = [];
      this.form.triggerId = [];
      this.conditionList.forEach((item) => {
        this.form.hostIds.push(item.hostId);
        this.form.triggerId.push(item.triggerid);
        ConditionsArr.push(
          "触发器" +
            (item.triggerOperator == 0 ? "等于 " : "不等于 ") +
            item.name
        );
      });
      this.form.conditions = ConditionsArr.join(","); //条件
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addAction_Api(this.form).then((res) => {
            this.$message.success("操作成功");
            this.dialogVisible = false;
            this.getList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //添加条件提交
    submitCondition() {
      //操作者
      this.form_condition.trigger_inp.forEach(
        (item) => (item.triggerOperator = this.form_condition.triggerOperator)
      );
      //条件表格 ，添加自愈时清空，在侦听器里
      this.conditionList = [
        ...this.conditionList,
        ...this.form_condition.trigger_inp,
      ];
      //条件表格去重，条件：主机id和触发器id
      this.conditionList = this.uniqueByProperty(
        this.conditionList,
        "hostId",
        "triggerid"
      );

      this.form.flag = Number(this.form_condition.flag);
      this.form.hostOperator = Number(this.form_condition.triggerOperator);
      this.form.triggerOperator = Number(this.form_condition.triggerOperator);
      this.dialogVisible_condition = false;
    },
    //确定选择触发器
    chooseTrigger() {
      this.dialogVisible_trigger = false;
      const { host } = this.hosts.find(
        (item) => item.hostid == this.form_trigger.host
      );
      this.multipleSelection.forEach((item) => {
        this.form_condition.trigger_inp.push({
          name: host + ": " + item.description,
          hostId: this.form_trigger.host,
          triggerid: item.triggerid,
        });
      });
      //触发器输入框去重，条件：主机id和触发器id
      this.form_condition.trigger_inp = this.uniqueByProperty(
        this.form_condition.trigger_inp,
        "hostId",
        "triggerid"
      );
    },
    //多选触发器
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //关闭弹窗
    closeDialog(formName) {
      this.$refs[formName].resetFields();
    },
    //数组对象去重
    uniqueByProperty(arr, property1, property2) {
      return arr.filter((item, index) => {
        // 使用 some 方法查找是否存在与当前项相同的项
        return !arr.some(function (obj, i) {
          return (
            obj[property1] === item[property1] &&
            obj[property2] === item[property2] &&
            i < index
          );
        });
      });
    },
    //展示修改状态
    showEdit(row) {
      this.editVisible = true;
      this.editForm = {
        actionid: row.actionId,
        status: row.status,
      };
    },
    //修改状态
    editAction(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res = await editAction_Api(this.editForm);
          let { code, msg } = res;
          if (code == 200) {
            this.$message.success(msg);
            this.getList();
            this.editVisible = false;
          } else {
            this.$message.error(msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //批量删除
    delAction() {
      let ids = this.multipleSelection.map((item) => {
        return item.actionId;
      });
      let data = ids.join("&params=");
      console.log(data);
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await delAction_Api(data);
          let { code, msg } = res;
          if (code == 200) {
            this.$message.success(msg);
            this.getList();
          } else {
            this.$message, error(msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.getList(); //获取故障自愈列表
    this.getHostList(); //获取主机列表数据
    this.getListData(); //获取脚本列表
  },
  watch: {
    "form.operationHostId": {
      handler(newVal) {
        this.getTriggerList(newVal[0]);
        this.form_trigger.host = newVal[0];
      },
    },
    //条件（2层
    dialogVisible_condition: {
      handler(newVal) {
        if (newVal) {
          this.form_condition.trigger_inp = [];
        }
      },
    },
    //触发器（3层
    dialogVisible_trigger: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection();
          });
        }
      },
    },
    //添加自愈（1层
    dialogVisible: {
      handler(newVal) {
        this.conditionList = [];
      },
    },
  },
  filters: {
    //过滤严重性
    getPriority(val) {
      switch (val) {
        case 0:
          return "未分类";
        case 1:
          return "信息";
        case 2:
          return "警告";
        case 3:
          return "一般严重";
        case 4:
          return "严重";
        case 5:
          return "灾难";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
//触发器输入框
.trigger_box {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  .trigger_inp {
    min-height: 30px;
    width: 300px;
    padding: 5px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;

    .choosed_Triggers {
      padding-left: 5px;
      max-width: 200px;
      overflow: hidden;
      height: 20px;
      font-size: 10px;
      line-height: 20px;
      background-color: #768d99;
      color: #ffffff;
      border-radius: 3px;
      margin-bottom: 5px;
    }
  }
}

.form_box {
  width: 100%;
  box-sizing: border-box;
  padding-right: 50px;
  max-height: calc(100vh - 300px);
  overflow-y: scroll;

  &::-webkit-scrollbar-track {
    background-color: #ffffff;
  }
}

.condition_box {
  border: 1px solid #e4dede;
  padding: 0 5px;

  th,
  td {
    height: 22px;
    line-height: 22px;
  }
}
</style>